package com.tensquare.base.controller;


import com.tensquare.base.doman.Label;
import com.tensquare.base.service.LabelService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/label")
public class LableController {

    @Autowired
    private LabelService labelService;
    /**
     * 标签增加
     */
   // @RequestMapping(value = "",method = RequestMethod.POST)
    @PostMapping("")  //替代RequestMapping注解
    public Result save(@RequestBody Label label){
        labelService.save(label);
        return new Result(true,StatusCode.OK,"增加成功");
    }

    /**
     * 查询单个标签
     */
    @GetMapping("{labelId}")  //动态传入参数   这种写法是直接拿路径上的值 例如:http://127.0.0.1:9001/label/1
    public Result findOne(@PathVariable(value="labelId") String labelIdx){
        Label label = labelService.findOne(labelIdx);
        return  new Result(true,StatusCode.OK,"查询成功",label);
    }
    /**
     * 查询所有标签
     */
    @GetMapping("")
    public Result findAll(){
       List<Label> labels =  labelService.findAll();
       return new Result(true,StatusCode.OK,"查询成功",labels);
    }
    /**
     * 更新
     */
    @PutMapping("{labelId}")
    public Result update(@PathVariable String labelId, @RequestBody Label label){
        label.setId(labelId);
        labelService.update(label);
        return new Result(true,StatusCode.OK,"更新成功");
    }
    /**
     * 删除
     */
    @DeleteMapping("{labelId}")
    public Result delete(@PathVariable String labelId){
        labelService.delete(labelId);
        return new Result(true,StatusCode.OK,"删除成功");
    }

    /**
     * 标签条件查询
     */
    @PostMapping("search")
    public Result search(@RequestBody Map map){
        List<Label> list = labelService.search(map);
        return new Result(true,StatusCode.OK,"查询成功",list);
    }

    /**
     * 根据条件分页查询
     * @param page 页码,页码0才是第一页
     * @param size  页面大小
     * @param map
     * @return
     */
    @PostMapping("/search/{page}/{size}")
    public Result search(@PathVariable int page,@PathVariable int size,@RequestBody Map map){
        //Pageable封装当前页，页大小
        Pageable pageable = PageRequest.of(page-1, size);
        //page对象中查询到总记录数,当前页记录
        Page pageData = labelService.search(map,pageable);
        //总记录数
        System.out.println(pageData.getTotalElements());
        //当前页记录
        System.out.println(pageData.getContent());
        PageResult<Label> pageResult = new PageResult<>(pageData.getTotalElements(),pageData.getContent());
        return new Result(true,StatusCode.OK,"查询成功",pageResult);
    }
}
